package randutil

import "math/rand"

// 如果max小于min，返回min
// 如果min等于0，返回0
func Range(min int, max int) int {
	if max < min {
		return min
	}
	if min == 0 {
		return min
	}
	return min + rand.Intn(max-min)
}

// key = 键, val=权重
func Weight(source map[int]int) int {

	var (
		prev int
		list []int
		m    = map[int]int{}
		max  int
	)

	count := 0
	for key, val := range source {
		cur := prev + val
		list = append(list, cur)
		m[count] = key
		count++

		prev = cur
		max = cur
	}

	if max == 0 {
		return 0
	}
	n := rand.Intn(max)
	idx := 0
	for i, val := range list {
		if n <= val {
			idx = i
			break
		}
	}

	return m[idx]
}

// key = 键, val=权重
func WeightString(source map[string]int) string {

	var (
		prev int
		list []int
		m    = map[int]string{}
		max  int
	)

	count := 0
	for key, val := range source {
		cur := prev + val
		list = append(list, cur)
		m[count] = key
		count++

		prev = cur
		max = cur
	}

	if max == 0 {
		return ""
	}
	n := rand.Intn(max)
	idx := 0
	for i, val := range list {
		if n <= val {
			idx = i
			break
		}
	}

	return m[idx]
}
